package com.example.schedule;

import com.alibaba.fastjson.JSONObject;
import com.example.constant.LogCollectionConstants;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.PutMappingRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.example.constant.LogCollectionConstants.DATE_FORMATTER_SECOND;

/**
 * description: EventLogSchedule
 * date: 2020/7/20 18:42
 * author: cheny
 * version: 1.0
 */
@Component
@Slf4j
public class CreateSchedule {

    @Autowired
    private RestHighLevelClient client;


    @Transactional
    @PostConstruct
    public void createWeekIndex() {
        // 返回值是布尔类型，判断方法是client对象下indices()方法的exists方法，在这个方法里有索引的名字；
        try {
          String indexName = LogCollectionConstants.WARN_INDEX_NAME_ALIAS + "_" +DATE_FORMATTER_SECOND.format(new Date());
          createIndex(indexName,"");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }



    public static void main(String[] args) {
        String indexName = LogCollectionConstants.WARN_INDEX_NAME_ALIAS + "_" +DATE_FORMATTER_SECOND.format(new Date());
        String  isAdd = "\""+ "123" + "\":{\"type\":\"keyword\"}";
        System.out.println(isAdd);
    }

    public void createIndex(String indexName,String isAdd) {
        try {
            boolean exists = client.indices().exists(new GetIndexRequest(indexName).humanReadable(true), RequestOptions.DEFAULT);
            log.info("索引：" + indexName + "是否存在：" + exists);
            if (exists) {
                return;
            }

            // 创建索引
            CreateIndexRequest request = new CreateIndexRequest(indexName);
            Map indexMap = new HashMap<>();
            indexMap.put("number_of_shards", "3");
            indexMap.put("number_of_replicas", "1");
            Map settings = new HashMap<>();
            settings.put("index", indexMap);
            request.settings(settings);
            CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
            boolean createAcknowledged = createIndexResponse.isAcknowledged();
            boolean createShardsAcknowledged = createIndexResponse.isShardsAcknowledged();
            log.info("创建索引acknowledged:" + createAcknowledged);
            log.info("创建索引shardsAcknowledged:" + createShardsAcknowledged);

            // 创建type
            String mappings = "{\"properties\":{$isAdd\"level\":{\"type\":\"keyword\"},\"mergeCount\":{\"type\":\"long\"},\"processStatus\":{\"type\":\"keyword\"},\"firstOccurTime\":{\"type\":\"date\"},\"lastOccurTime\":{\"type\":\"date\"},\"createTime\":{\"type\":\"date\"}}}";
            mappings = mappings.replace("$isAdd",isAdd);
            PutMappingRequest putMappingRequest = new PutMappingRequest(indexName);
            putMappingRequest.source(mappings, XContentType.JSON);
            AcknowledgedResponse mappingResponse = client.indices().putMapping(putMappingRequest, RequestOptions.DEFAULT);
            boolean mappingResult = mappingResponse.isAcknowledged();
            log.info("mapping映射创建结果:" + mappingResult);

//            //更新别名
//            IndicesAliasesRequest aliasesRequest = new IndicesAliasesRequest();
//            IndicesAliasesRequest.AliasActions aliasAction =
//                    new IndicesAliasesRequest.AliasActions(IndicesAliasesRequest.AliasActions.Type.ADD)
//                            .index(indexName).alias(LogCollectionConstants.LOG_INDEX_NAME_ALIAS);
//            aliasesRequest.addAliasAction(aliasAction);
//            AcknowledgedResponse indicesAliasesResponse =
//                    client.indices().updateAliases(aliasesRequest, RequestOptions.DEFAULT);
//            boolean acknowledged = indicesAliasesResponse.isAcknowledged();
//            log.info("别名更新结果:" + acknowledged);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }

    }


}
